package cn.haoxsf.app.system.service.impl;

import cn.haoxsf.app.common.api.enums.ImagesExceptionEnum;
import cn.haoxsf.app.common.api.enums.UserExceptionEnum;
import cn.haoxsf.app.common.exception.BaseException;
import cn.haoxsf.app.common.util.ToolUtil;
import cn.haoxsf.app.system.entity.FileInfo;
import cn.haoxsf.app.system.mapper.FileInfoMapper;
import cn.haoxsf.app.system.service.IAuthService;
import cn.haoxsf.app.system.service.IFileInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 文件信息表 服务实现类
 * </p>
 *
 * @author Ele  qvbanfm@qq.com
 * @since 2020-01-09
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements IFileInfoService {
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private Auth auth;
    @Autowired
    private IAuthService authService;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.path}")
    private String url;
    private StringMap putPolicy;
    private Configuration cfg = new Configuration(Region.region0());


    /**
     * 直接用输入流上传至七牛
     *
     * @param file 上传的文件
     *             生成唯一id
     * @return FileInfo
     * @throws IOException BaseException
     */
    @Override
    public Collection<FileInfo> uploadImages(MultipartFile[] file) throws IOException, BaseException {
        Long userId = authService.getLoginUser().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new BaseException(UserExceptionEnum.NOT_USERS);
        }
        Collection<FileInfo> imagesList = new ArrayList<>();
        if (ToolUtil.isNotEmpty(file)) {//遍历输入流
            for (MultipartFile aFile : file) {
                InputStream inputStream = aFile.getInputStream();
                Response put = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
                if (ToolUtil.isEmpty(put)) {
                    throw new BaseException(ImagesExceptionEnum.IMAGE_UPLOAD_ERROR);
                }
                DefaultPutRet putRet = new Gson().fromJson(put.bodyString(), DefaultPutRet.class);
                //创建图片对象
                FileInfo image = new FileInfo();
                image.setFileId(UUID.randomUUID().toString().replace("-",""));
                image.setFileBucket("QINIU");
                image.setCreateTime(new Date());
                image.setCreateUser(userId);
                image.setFilePath(url + "/" + putRet.hash);
                image.setFileName(aFile.getOriginalFilename().split("\\.")[0]);
                image.setFileSuffix(aFile.getOriginalFilename().split("\\.")[1]);
                image.setFileSizeKb(aFile.getSize());
                image.setFinalName(UUID.randomUUID().toString().replace("-",""));
                imagesList.add(image);
            }
            this.saveOrUpdateBatch(imagesList);

        }else {
            return null;
        }
        return imagesList;
    }
//    @Override
//    public void deleteImages(String imagesName) throws QiniuException {
//        BucketManager bucketManager = new BucketManager(auth, cfg);
//        List<FileInfo> infoList = this.list();
//        if (ToolUtil.isNotEmpty(infoList)) {
//            for (FileInfo sysFileInfo : infoList) {
//                if (sysFileInfo.getFinalName().equals(imagesName)) {
//                    Response response = bucketManager.delete(bucket, sysFileInfo.getFilePath().substring(sysFileInfo.getFilePath().lastIndexOf("/") + 1));
//                    this.baseMapper.deleteById(sysFileInfo.getFileId());
//                    if (!response.isOK()) {
//                        throw new BaseException(ImagesExceptionEnum.IMAGES_NAME_IS_EMPTY);
//                    }
//                }
//            }
//        }
//    }
    /**
     * 删图片
     *
     * @param finalName 图片唯一名称
     */
    public void deleteImages(String  finalName) throws QiniuException{
        BucketManager bucketManager = new BucketManager(auth, cfg);
        FileInfo fileInfo = this.baseMapper.selectOne(new QueryWrapper<FileInfo>().eq("final_name", finalName));
        if(ToolUtil.isEmpty(fileInfo)){
            throw new BaseException(ImagesExceptionEnum.IMAGES_NAME_IS_EMPTY);
        }
        Response delete = bucketManager.delete(bucket,
                fileInfo.getFilePath().substring(fileInfo.getFilePath().lastIndexOf("/") + 1));
        this.baseMapper.deleteById(fileInfo.getFileId());
        if (!delete.isOK()) {
            throw new BaseException(ImagesExceptionEnum.IMAGES_NAME_IS_EMPTY);
        }
    }

    /**
     * 按照FinalNames 批量查询
     *
     * @param FinalNames
     * @return
     */
    @Override
    public List<Map<String,Object>> selectBatchFinalNames(String[] FinalNames) {
        return baseMapper.selectBatchFinalNames(FinalNames);
    }

    private String getUploadToken() {
        return this.auth.uploadToken(bucket, null, 3600, putPolicy);
    }
}
